'use strict';

const { Wallets} = require('fabric-network');
const FabricCAServices = require('fabric-ca-client');
const path = require('path');
const { buildCAClient, registerAndEnrollUser, enrollAdmin } = require('../jsUtils/CAUtil.js');
const { buildCCPOrg1,buildCCPOrg2,buildCCPOrg3, buildWallet } = require('../jsUtils/AppUtil.js');

const mspOrg1 = 'Org1MSP';
const mspOrg2='Org2MSP';
const mspOrg3='Org3MSP';

const walletPathOrg1 = path.join(__dirname, 'walletOrg1');
const walletPathOrg2 = path.join(__dirname, 'walletOrg2'); 
const walletPathOrg3 = path.join(__dirname, 'walletOrg3');

const org1d1 = 'org1repo';
const org1d2 = 'org1transfer';
const org2d1 = 'school';
const org2d2 = 'buyer';
const org3d1 = 'org3repo';
const org3d2 = 'org3transfer';

async function createWallets(){
	try{
        //create walletOrg1
		const ccp1 = buildCCPOrg1();
		const caClient1 = buildCAClient(FabricCAServices, ccp1, 'ca.org1.project.com');
		const walletOrg1 = await buildWallet(Wallets, walletPathOrg1);
		await enrollAdmin(caClient1, walletOrg1, mspOrg1);
		await registerAndEnrollUser(caClient1, walletOrg1, mspOrg1, org1d1, 'org1.department1');
        await registerAndEnrollUser(caClient1, walletOrg1, mspOrg1, org1d2, 'org1.department2');
		
        //create walletOrg2
		const ccp2 = buildCCPOrg2();
		const caClient2 = buildCAClient(FabricCAServices, ccp2, 'ca.org2.project.com');
		const walletOrg2 = await buildWallet(Wallets, walletPathOrg2);
		await enrollAdmin(caClient2, walletOrg2, mspOrg2);
		await registerAndEnrollUser(caClient2, walletOrg2, mspOrg2, org2d1, 'org2.department1');
        await registerAndEnrollUser(caClient2, walletOrg2, mspOrg2, org2d2, 'org2.department2');

        //create walletOrg3
		const ccp3 = buildCCPOrg3();
		const caClient3 = buildCAClient(FabricCAServices, ccp3, 'ca.org3.project.com');
		const walletOrg3 = await buildWallet(Wallets, walletPathOrg3);
		await enrollAdmin(caClient3, walletOrg3, mspOrg3);
		await registerAndEnrollUser(caClient3, walletOrg3, mspOrg3, org3d1, 'org3.department1');
        await registerAndEnrollUser(caClient3, walletOrg3, mspOrg3, org3d2, 'org3.department2');
      	    
    }catch(error){
		console.error(`FAILED to run the application: ${error}`);
	}	
}

function main(){
    createWallets();
}

main();